<?php
/**
 * standard functions
 *
 * @author Sven Ruttloff, www.sruttloff.de <service@sruttloff.de>
 * @copyright S.Ruttloff, Computer Hard- & Software
 * @package core
 * @license http://www.sruttloff.de/cms/files/licence_en_lgpl.txt LGPL
 * @version 1
 */

/**
 * Send a Redirect HEADER to the browser
 *
 * @param   	string    redirect target
 * @return		void
 */
function redirect($target = '')
{
    if (!$target)
        $target = $_SERVER['REQUEST_URI'];
    // add SID
    if (SID)
    {
        // check if a var is in url
        if (preg_match ("=\?=", $target))
        $target .= "&".SID;
        else
        $target .= "?".SID;
    }
    header("Location: $target");
    exit;
}

/**
 * Delete a directory
 *
 * @param      string    complete dir path to empty
 * @param 	   int		 if 0 given dir will be deleted too
 * @return     bool
 */
function kill_dir($dir, $subthread = 0)
{
    if ($open = @ opendir($dir)) {
        while ($file = readdir($open)) {
            if ($file != "." && $file != "..") {
                $newdir = $dir . "/" . $file;
                if (is_dir($newdir)) {
                    kill_dir($newdir, 1);
                    rmdir($newdir);
                } else
                @ unlink($newdir);
            }
        }
        closedir($open);
        if (!$subthread)
        rmdir($dir);
    } else
    return false;
    return true;
}
/**
 * return a get or post variable, in the order get, post
 *
 * @param      string    $var variable name
 * @return     mixed     content of $var
 */
function sendvar($var = "") {
    if (isset ($_POST[$var]))
    return $_POST[$var];
    if (isset ($_GET[$var]))
    return $_GET[$var];
    return false;
}
/**
 * add slashes to array values
 *
 * @param array
 * @return array slashes added values
 */
function addslashesSendvarArray ($var) {
    foreach ($var as $k=>$v) {
        if (is_array($v))
        $var[$k] = addslashesSendvarArray ($v);
        else
        $var[$k] = addslashes($v);
    }
    return $var;
}
/**
 * secure post and get vars
 */
function secureVars () {
    if (isset($_POST))
    foreach ($_POST as $k=>$v) {
        if (is_array($v))
        $_POST[$k] = addslashesSendvarArray($v);
        else
        $_POST[$k] = addslashes($v);
    }
    if (isset($_GET))
    foreach ($_GET as $k=>$v) {
        if (is_array($v))
        $_GET[$k] = addslashesSendvarArray($v);
        else
        $_GET[$k] = addslashes($v);
    }
}
/**
 * sets a get and post variable
 *
 * @param      string    name of the var
 * @param      string    content of the var
 * @return     true
 */
function sendvar_set($name, $val = "") {
    $_POST[$name] = $val;
    $_GET[$name] = $val;
    return true;
}
/**
 * check if a get and post variable is set, order is POST, GET
 *
 * @param      string    name of the var
 * @return     bool
 */
function isset_sendvar($var) {
    if ($var == "")
    return false;
    if (isset ($_POST[$var]))
    return TRUE;
    elseif (isset ($_GET[$var])) return TRUE;
    else
    return FALSE;
}

/**
 * Checks a given email adress for validity
 *
 * @param      string    email adress
 * @return     bool
 */
function check_mail($email) {
    $valid = "^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}$";
    if (eregi($valid, $email))
    return true;
    else
    return false;
}
/**
 * Checks a given string for numbers only
 *
 * @param      string
 * @return     bool
 */
function check_nums_only($string = "") {
    $valid = "=^[0-9]+$=s";
    return preg_match($valid, $string);
}
/**
 * Create a directory
 *
 * @param      string    path
 * @param	   mixed	 false or a CHMOD as string
 * @return     bool
 */
function create_dir($path, $chmod = false) {
    if (is_dir($path))
    return true;
    if ($chmod)
    return mkdir($path, intval($chmod, 8));
    else
    return mkdir($path);
}
/**
 * Create a file with or without a CHMOD
 *
 * @param    string    	filename including absolute path
 * @param    string	 	file content
 * @param	   	mixed     CHMOD of the file
 * @param		int			max file length
 * @return		bool
 */
function create_file($file = "", $content = "", $chmod = false, $length = false) {
    if (!$fp = fopen($file, "w+"))
    return false;
    else
    {
        if ($length)
        fwrite($fp, $content, $length);
        else
        fwrite($fp, $content);
        fclose($fp);
        if ($chmod != false)
        chmod($file, intval($chmod, 8));
    }
    return true;
}
/**
 * copies file from source to target, keeps also symlinks!
 *
 * @param      string    source file
 * @param      string    target file
 * @param      bool      true = overwrite
 * @return     bool
 */
function copy_file($source, $target, $overwrite = false, $chmod = false)
{
    //prüfen ob target existiert
    if (file_exists($target))
    {
        //soll gelöscht werden
        if ($overwrite)
        {
            if (!@ unlink($target))
                return "&09";
        }
        else
            return "&10";
    }
    // check if it is symlink
    if (linkinfo ($source))
    {
        // its a link
        $source =  readlink ($source);
        // create symlink
        if (symlink ( $source, $target))
            return true;
        else
            return false;
    }
    else
    {
        if (!@ copy($source, $target))
            return false;
    }
    if ($chmod)
        @ chmod($target, intval($chmod, 8));
    return true;
}
/*
 * replaces newline to <br> if no new line HTML Tags are used in text
 *
 * @param		string		text
 * @return      string		HTML Formated text
 */
function own_nl2br($text) {
    if (!preg_match("=(<br>|<br/>|<br />|</td>|</tr>|</p>|</div>)=siU", $text))
    return nl2br($text);
    else
    return $text;
}
/*
 * returns the referer
 *
 * @return      mixed      false if no referer else the referer
 */
function refererinfo() {
    if (!$_SERVER['HTTP_REFERER'])
    return false;
    return parse_url($_SERVER['HTTP_REFERER']);
}
/*
 * returns the actual time as microtime
 *
 * @return      float
 */
function getmicrotime() {
    list ($usec, $sec) = explode(" ", microtime());
    return ((float) $usec + (float) $sec);
}
/*
 * returns the formated filesize
 * @param       int       	filesize in bytes
 * @return      string      filesize in KB,MB or GB
 */
function my_filesize($size) {
    if ($size < 1024)
    $result = $size . ' Byte';
    else {
        $result = round($size / 1024, 2);
        if ($result < 1024)
        $result .= ' KB';
        else
        $result = round($result / 1024, 2) . ' MB';
        if ($result > 1024)
        $result = round($result / 1024, 2) . ' GB';
    }
    return $result;
}
/**
 * Errorhandler
 *
 * @access     private
 */
function myErrorHandler($errno, $errstr, $errfile, $errline) {
    /*	Bitwert	Konstante
     1	E_ERROR
     2	E_WARNING
     4	E_PARSE
     8	E_NOTICE
     16	E_CORE_ERROR
     32	E_CORE_WARNING
     64	E_COMPILE_ERROR
     128	E_COMPILE_WARNING
     256	E_USER_ERROR
     512	E_USER_WARNING
     1024	E_USER_NOTICE
     2047	E_ALL
     2048	E_STRICT
     */

    switch ($errno) {
        case "2" :
        case "8" : #notiz
        case "2048" :
            break;
        default :
            $raw = debug_backtrace();
            $output="";
            foreach($raw as $entry){
                $output.="\nFile: " . (isset($entry['file']) ? $entry['file'] : '-')." (Line: " . (isset($entry['line']) ? $entry['line'] : '-') . ")\n";
                $output.="Function: ".$entry['function']."\n";
                if (isset($entry['args'])) {
                    $output.="Args: " . CMSRFEErrorHandlerHelper($entry['args']) .  "\n";
                }
            }
            $message = "Error no.: $errno\n" . "File: " . basename($errfile) . "\n" . "Line: $errline\n" . "Error text: $errstr\n";
            #$message .= "\nBacktrace:\n" . implode("\n", debug_backtrace());
            $message .= "\nBacktrace:\n" . $output;

            echo nl2br($message);
            break;
    }
}
function myExceptionHandler ($e = null)
{
    trigger_error($e->getMessage(), E_USER_ERROR);
}
function CMSRFEErrorHandlerHelper ($args) {
    $output = '';
    foreach ($args as $arg) {
        if ($output)
        $output .= ', ';
        switch (true) {
            case is_array($arg) :
                $arg = 'array:' . CMSRFEErrorHandlerHelper ($arg);
            case is_object($arg) :
                $arg = 'Class:' . get_class($arg);
                break;
            default:
                break;
        }
        $output .=  $arg;
    }
    return $output;
}
/**
 * Return browse elements
 *
 * @param      int    	quantity of datas to browse
 * @param      int    	display limit (default: 10)
 * @param      int    	active element
 * @param      int    	maximum browse elements (default: 10)
 *
 * @return     array    array with numbered Elements
 *
 * @access     public
 */
function BrowseDatas($totaldatas = 0, $limit = 10, $active = 0, $maxelements = 10) {
    $rewind = $forward = $offsets = array ();
    if (!$active)
    $active = 0;
    # rewind an forward elements
    if ($active) {
        $offsets = array (
        htmlentities("<"
        ) => 0, htmlentities("<<") => ($active - $limit));
        $maxelements += count($offsets);
    }
    // calc. how many pages we have
    $possiblepages =  floor(($totaldatas-1) / $limit);
    for ($i = 0; $i <= $possiblepages; $i++) {
        if (count($offsets) >= $maxelements)
        break;
        if (($i +1) < $possiblepages - $maxelements +3)
        if (($i +1) < ($active / $limit) - (($maxelements -5) / 2))
        continue;
        $offsets[($i +1)] = $i * $limit;
    }
    if ($active / $limit < $possiblepages) {
        $offsets[htmlentities(">>")] = ($active + $limit);
        $offsets[htmlentities(">")] = (integer) ($totaldatas / $limit) * $limit;
    }
    return count($offsets) > 1 ? $offsets : array ();
}
/**
 * Better var_dump
 *
 * @param      	mixed   	variable to dump
 * @return		void
 */
function debug_var($mixed) {
    echo '<pre>';
    var_dump($mixed);
    echo '</pre>';
    return null;
}
/**
 * return the extension of a file
 *
 * @param		string		filename
 * @return     	string		file extension
 */
function FileExtension ($filename = null){
    preg_match ("=\.(\w*)$=i", $filename, $temp);
    return $temp[1];
}
/**
 * return a unique password
 *
 * @param		int			password length
 * @return     	string		password
 */
function create_password($number = 4) {
    $zeichen = "qwertzupasdfghkyxcvbnm";
    $zeichen .= "123456789";
    $zeichen .= "WERTZUPLKJHGFDSAYXCVBNM";
    srand((double) microtime() * 1000000);
    for ($i = 0; $i < $number; $i++) {
        $password .= substr($zeichen, (rand() % (strlen($zeichen))), 1);
    }
    return $password;
}
/**
 * return a unique password, alias for create_password
 *
 * @param int password length
 * @return string password
 */
function createPassword($number = null)
{
    return create_password($number);
}
/**
 * return a quotet string
 *
 * @param		string
 * @return     	string
 */
function SavePrint ($text = null) {
    echo HtmlFormat ($text);
}
/**
 * returns a html string
 *
 *@param		string		text to convert
 *@return     	string
 */
function HtmlFormat ($string = null) {
    return htmlentities($string, ENT_QUOTES , "UTF-8");
}
/**
 * returns a non html valid string
 *
 *@param		string		text to convert
 *@return     	string
 */
function UnHtmlFormat ($string = null) {
    return html_entity_decode($string, ENT_QUOTES , "UTF-8");
}
/**
 * convert arbitrary num values to formated values with its own fp separator
 *
 * @param		float		number to format
 * @param		int			how many nums after separator
 * @param		string		comma separator (default = ,)
 * @return     	string
 */
function CurFormat ($value = 0, $places = 2, $returnsep = ",") {
    return str_replace(".", $returnsep, sprintf("%01." . $places . "f", str_replace(",", ".", $value)));
}
/**
 * convert multibyte strings (utf-8) and unserialize it
 *
 *@param		string		serialized var
 *@return     	mixed		var
 */
function mb_unserialize($serial_str) {
    // try to unserialize
    $return = unserialize($serial_str);
    return $return ? $return : unserialize(utf8_encode($serial_str));
}
/**
 * convert standard date in iso format eg. 01.12.1970 to 1970-12-01
 *
 *@param		string		 var
 *@return     	mixed		return false if in date is not a valid std.format
 */
function DateStdToIso ($date) {
    if (!preg_match("=\d{1,2}\.\d{1,2}\.\d{2,4}=", $date))
    return false;
    $temp = explode (".", $date);
    if (count ($temp) != 3)
    return false;
    return (strlen($temp[2]) == 2 ? '19' . $temp[2] : $temp[2]) . "-" . $temp[1] . "-" . $temp[0];

}
/**
 * convert standard iso date in std format eg. 1970-12-01 to 01.12.1970
 *
 *@param		string		 var
 *@return     	mixed		return false if in date is not a valid std.format
 */
function DateIsoToStd ($date) {
    // strip may included time
    $date = preg_replace ("=\s\d{2}:\d{2}:\d{2}$=", "", $date);
    if (!preg_match("=\d{4}-\d{1,2}-\d{1,2}=", $date))
    return false;
    $temp = explode ("-", $date);
    if (count ($temp) != 3)
    return false;
    return $temp[2] . "." . $temp[1] . "." . $temp[0];

}
/**
 * convert standard iso date in unix time stamp format eg. 1970-12-01 to 15672376823
 *
 *@param		string		var
 *@return     	mixed		return false if in date is not a valid std.format
 */
function DateIsoToStamp ($date) {
    // strip may included time
    $date = preg_replace ("=\s\d{2}:\d{2}:\d{2}$=", "", $date);
    if (!preg_match("=\d{4}-\d{1,2}-\d{1,2}=", $date))
    return false;
    $temp = explode ("-", $date);
    if (count ($temp) != 3)
    return false;
    return mktime(0, 0, 0, $temp[1] , $temp[2] , $temp[0]);

}
/**
 * split a set of words
 *
 * @param		string		input string
 * @param		int			string len max
 * @param		string		continue string e.g. ...
 * @return     	string		cuted string
 */
function _WordWrap($xstr, $xlenint, $xlaststr) {
    if (strlen($xstr) < $xlenint)
    return $xstr;
    $xlenintnew = strpos($xstr, " ", $xlenint);
    if ($xlenintnew)
    $xlenint = $xlenintnew;
    return substr($xstr, 0, $xlenint) . $xlaststr;
}
/**
 * return web url path, for base tags
 *
 * @return string
 */
function getRequestPath ()
{
    $url = (string) null;
    switch ($_SERVER['SERVER_PORT']) {
        case '80':
        default:
            $url .= 'http://';
            break;
    }
    $url .= $_SERVER['SERVER_NAME'];
    $path = $_SERVER['REQUEST_URI'];
    if (!preg_match ('|.*/$|', $path))
    $url .= dirname($path) . '/';
    else
    $url .= $path;
    return $url;
}
